#include "ToastDialog.h"

ToastDialog*ToastDialog::create(const char* str, uint sec)
{
	ToastDialog* ret = new ToastDialog();
	if (ret && ret->init(str, sec)) {
		ret->autorelease();
		return ret;
	} else {
		delete ret;
		return NULL;
	}
}

bool ToastDialog::init(const char* str, uint sec)
{
	bool bRet = false;
	do {
		CCScale9Sprite::initWithFile(CCRectMake(7, 8, 350, 110),
		                             "dialog/progress_bg.png");
		_strLbl = CCLabelTTF::create("", "DroidSansFallbackFull", 12);
		CC_BREAK_IF(!_strLbl);
		_strLbl->setAnchorPoint(ccp(0.5, 0.5));
		_strLbl->setPosition(CCPointZero);
		this->addChild(_strLbl);
		_showing = false;
		updateStr(str);

		setDismiss(sec);
		bRet = true;
	}while(0);
	return bRet;
}

void ToastDialog::updateStr(const char* str)
{
	if (!str) {
		str = "";
		return;
	}
	if (strcmp(str, _strLbl->getString())) {
		_strLbl->setString(str);
		this->setContentSize(CCSizeMake(_strLbl->getContentSize().width + 16,
						_strLbl->getContentSize().height + 16));
		_strLbl->setPosition(ccp(this->getContentSize().width /2 ,
					 this->getContentSize().height / 2));
	}
}

int ToastDialog::show()
{
	CCScene* s = CCDirector::sharedDirector()->getRunningScene();
	this->setOpacity(255);
	if (s && !_showing) {
		CCSize winSize = CCDirector::sharedDirector()->getWinSize();
		_showing = true;
		this->setPosition(ccp(winSize.width / 2, winSize.height * 0.3));
		s->addChild(this);
		return 0;
	}
	return -1;
}

void ToastDialog::setDismiss(const uint sec)
{
	if (sec > 0) {
		this->stopAllActions();
		this->unschedule(schedule_selector(ToastDialog::dismiss));
		_time = sec;
		this->schedule(schedule_selector(ToastDialog::dismiss), 1.0f);
	}
}

void ToastDialog::dismiss(float dt)
{
	--_time;
	if (0 == _time) {
		this->unschedule(schedule_selector(ToastDialog::dismiss));
		this->runAction(CCSequence::create(
					CCFadeOut::create(0.5f),
					CCCallFunc::create(this, callfunc_selector(ToastDialog::removeMeCB)),
					NULL));
	}
}

void ToastDialog::removeMeCB()
{
	_showing = false;
	this->removeFromParentAndCleanup(true);
}
